#include "HttpServer.hpp"
#include "Usage.hpp"
#include "Util.hpp"

#include <memory>
#include <fstream>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define ROOT "./wwwroot"
#define HOMEPAGE "/index.html"

void HandlerHttpRequest(int sock)
{
    // 1. 读取请求
    char buffer[10240];
    ssize_t s = recv(sock, buffer, sizeof(buffer) - 1, 0);
    if (s > 0)
    {
        buffer[s] = 0;
    } 
    std::cout << buffer << "-----------------------\n" << std::endl;
    std::vector<std::string> vline;
    Util::cutString(buffer, "\r\n", &vline);
    std::vector<std::string> vblock;
    Util::cutString(vline[0], " ", &vblock);

    std::string file = vblock[1];
    std::string target = ROOT;

    if (file == "/") file = HOMEPAGE;
    target += file;
    std::cout << target << std::endl << std::endl;;

    // if (file == "/")
    // {
    //     target += "/src";
    //     target +=  HOMEPAGE;
    // }
    // else
    // {
    //     target += file;
    // }

    // C++文件操作
    std::string connect;
    std::ifstream in(target);
    if (in.is_open())
    {
        std::string line;
        while (std::getline(in, line))
        {
            connect += line;
        }
        in.close();
    }
    std::string HttpResponse;
    if (connect.empty())
    {
        HttpResponse = "HTTP/1.1 302 Found\r\n";
        HttpResponse += "Location:https://www.csdn.net/";
    }
    else HttpResponse = "HTTP/1.1 200 OK\r\n";
    HttpResponse += "\r\n";
    HttpResponse += connect;
    send(sock, HttpResponse.c_str(), HttpResponse.size(), 0);


    // 2. 模拟响应
    // std::string HttpResponse = "HTTP/1.1 200 OK\r\n";
    // HttpResponse += "\r\n";
    // HttpResponse += "<html><h3>Hello Http</h3></html>";
    // send(sock, HttpResponse.c_str(), HttpResponse.size(), 0);
}

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::unique_ptr<HttpServer> httpserver(new HttpServer(atoi(argv[1]), HandlerHttpRequest));
    httpserver->Start();

    return 0;
}